<?
require_once("mvc/action/Action.php");
require_once("cms/newsletter/om/NewsletterPeer.php");
require_once("cms/newsletter/om/NewsletterPeer.php");
require_once("cms/newsletter/om/NewsletterSubscriberPeer.php");

class SendAction extends Action {

    private $log;

    public function __construct() {
        $this->log =& LoggerManager::getLogger("SendAction");
    }

    public function execute(ActionConfig &$mapping, &$form, Request &$request, Response &$response) {

        $recipients = $form->getRecipients();
        $errors = new ActionMessages();

        $conn = Propel::getConnection();

        try {

            $conn->begin();

            $c = new Criteria();
            $c->add(NewsletterSubscriberPeer::NEWSLETTER_ID, $form->getId());
            $c->add(NewsletterSubscriberPeer::RECEIVED, false);
            NewsletterSubscriberPeer::doDelete($c, $conn);

            foreach($recipients as $subscriberId) {
                $newsletterSubscriber = new NewsletterSubscriber();
                $newsletterSubscriber->setSubscriberId($subscriberId);
                $newsletterSubscriber->setNewsletterId($form->getId());
                NewsletterSubscriberPeer::doInsert($newsletterSubscriber, $conn);
            }

            $conn->commit();

        } catch(PropelException $e) {

            $conn->rollback();
            $errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("error.send"));
            $this->log->error($e);

        }

        if($errors->isEmpty()) {

            // Start sending email
            set_time_limit(0);

            require_once "swift/Swift.php";
            require_once "swift/Swift/Connection/NativeMail.php";

            try {

                $newsletter = NewsletterPeer::retrieveByPk($form->getId());
                $newsletter->setSentDate(date(_Core::FORMAT_SQLDATETIME));
                $newsletter->setStatus("partial");
                NewsletterPeer::doUpdate($newsletter);

                $c = new Criteria();
                $c->add(NewsletterSubscriberPeer::NEWSLETTER_ID, $form->getId());
                $newsletterSubscribers = NewsletterSubscriberPeer::doSelectJoinNewsletter($c);

                // get some i18n resources
                $resources =
                    $request->getContext()->getAttribute("php-cms-newsletternewsletter");

                // Start Swift
                $swift = new Swift(new Swift_Connection_NativeMail());

                // Create the message
                $message = new Swift_Message($newsletter->getSubject());

                // Calculate base address
                $base = "http://".$request->getServerName().
                    ($request->getServerPort() != 80 ? ":".$request->getServerPort() : "").
                    CONTEXTPATH."/";

                ob_start();
                include($request->getContext()->getInitParameter(_Newsletter::HEADER));
                $header = ob_get_contents();
                ob_end_clean();

                ob_start();
                include($request->getContext()->getInitParameter(_Newsletter::FOOTER));
                $footer = ob_get_contents();
                ob_end_clean();

                $count = 0;
                foreach($newsletterSubscribers as $newsletterSubscriber) {

                    try {

                        $locale  = new Locale("en");
                        $text    = $resources->getMessage($locale, "mail.text");

                        // Add some plain text
                        // Todo: Provide online newsletter link.
                        $message->attach(
                            new Swift_Message_Part(
                                $text, "text/plain", null, "utf-8"));

                        $body = str_replace(
                                    array("{base}", "{name}", "{key}"),
                                    array($base, "Tester", md5($newsletterSubscriber->getSubscriber()->getEmail())),
                                    ($header.$newsletter->getBody()->getContents().$footer)
                                );

                        // Add html
//                        $body = $header.$newsletter->getBody().$footer;

                        $message->attach(new Swift_Message_Part($body, "text/html", null, "utf-8"));

                        //Now check if Swift actually sends it
                        $swift->send($message, $newsletterSubscriber->getSubscriber()->getEmail(),
                            $request->getContext()->getInitParameter("EMAIL_FROM"));

                        // Update newsletter sent status
                        $newsletterSubscriber->setReceived(true);
                        NewsletterSubscriberPeer::doUpdate($newsletterSubscriber);

                        if($count++ == 0 && count($newsletterSubscribers) > 1) {
                            $newsletter->setStatus("partial");
                            NewsletterPeer::doUpdate($newsletter);
                        }

                    } catch (Swift_Connection_Exception $e) {
                        $errors->add(ActionMessage::GLOBAL_MESSAGE,
                            new ActionMessage("error.mail", true));
                        $this->log->errors($e);
                    } catch (Swift_Message_MimeException $e) {
                        $errors->add(ActionMessage::GLOBAL_MESSAGE,
                            new ActionMessage("error.message", true));
                        $this->log->errors($e);
                    }

                }

                $newsletter->setStatus("sent");
                NewsletterPeer::doUpdate($newsletter);

            } catch(PropelException $e) {

                $errors->add(ActionMessage::GLOBAL_MESSAGE,
                    new ActionMessage("error.send"));
                $this->log->error($e);

            }

        }


        // Return any save errors.
        if(!$errors->isEmpty()) {
            $this->saveErrors($request, $errors);
            return $mapping->getInputForward();
        }


        return $mapping->findForward("success");

    }

}
?>